package com.hongxun.design.activitys;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.PhotoGraphAdapter;
import com.hongxun.design.bean.BackPhotoBean;
import com.hongxun.design.bean.BackPhoto_Bean;
import com.hongxun.design.bean.BackPhotosBean;
import com.hongxun.design.bean.PhotoGraphBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.jbean.JPathBean;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.CheckClickTime;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.NoScrollListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PhotosActivityUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.httputil.PostParams;
import com.hongxun.design.utils.pathutil.ClipPathUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/5/11.
 * 拍照界面
 */
public class PhotoGraphActivity extends BaseActivity implements HeadSecond {
    NoScrollListView photograph_list;
    static PhotoGraphAdapter adapter;
    static List<PhotoGraphBean> listData;
    Handler expPhotoList;
    public static Handler savePhotoHandler;
    private List<Integer> type = new ArrayList<>();

    String exploration_id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            MyApp.userInfo.setBean(FastJsonUtil.JsonToLoginData(savedInstanceState.getString("userInfo")));
            MyApp.currExploration = FastJsonUtil.JsonToGetExplorInfo(savedInstanceState.getString("exploration_id"));
        }
        exploration_id = MyApp.currExploration.getExploration_id();
        setContentView(R.layout.activity_photograph);
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyApp.activity = this;
        mActivity = this;
        baseActivity = this;
    }

    @Override
    protected void onDestroy() {
        bean = null;
        super.onDestroy();
    }

    @Override
    public void findBar() {
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.photograph_title);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, ListenerSet.back, MString.PhotoGraph, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
    }

    @Override
    protected void findView() {
        findBar();
        bean = null;
        //下方按钮初始化
        TextView finish_button = (TextView) findViewById(R.id.photograph_finish_button);
        TextView continue_button = (TextView) findViewById(R.id.photograph_continue_button);
        SetTypeface.set(finish_button, IconSourse.SURE);
        SetTypeface.set(continue_button, IconSourse.PHOTOGRAPH);
        finish_button.append(" 直接完成");
        continue_button.append(" 继续设计");
        if (!MyApp.currExploration.getPt_type().equals(Constant.LOCALPOINT)) {
            continue_button.setVisibility(View.GONE);
        }
        if (MyApp.ReadOnly) {
            finish_button.setBackgroundResource(R.drawable.gray_item_6);
        }
        //listview控件初始化
        photograph_list = (NoScrollListView) findViewById(R.id.photograph_list);
        initialization();
        super.findView();
    }

    @Override
    protected void initialization() {
        addsavePhotosHandler();//保存照片hander
        getExpPhotoList();
        super.initialization();
    }

    /**
     * 查询踏勘照片*
     */
    public void getExpPhotoList() {
        addExpPhotoListHandler();
        String s = GetFileUtil.getExplorationPhotoList();
        if (TextUtils.isEmpty(s)) {
            if (MyApp.isOnLine) {
                MyApp.HTTP.getExpPhotoList(expPhotoList, HttpStringUtil.SUCCESSED, exploration_id);
            } else {
                bean = GetFileUtil.getExplorationPhoto();
                expPhotoList.sendEmptyMessage(1);
            }
        } else {
            expPhotoList.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, s));
        }
//        }
    }

    static BackPhotosBean bean;

    private void addExpPhotoListHandler() {
        expPhotoList = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (!MyApp.isOnLine) {
                                SetFileUtil.setExplorationPhotoOld((String) msg.obj);
                            }
                            bean = FastJsonUtil.JsonToData_BackPhotos((String) msg.obj);
                        }
                        expPhotoList.sendEmptyMessage(1);
                        break;
                    case 1:
                        if (listData != null)
                            listData.clear();
                        listData = null;
                        if (!MyApp.currExploration.getPt_type().equals(Constant.LOCALPOINT)) {
                            listData = DataUtil.getPhotoGraphData(bean, false);
                        } else {
                            listData = DataUtil.getPhotoGraphData(bean, true);
                        }
                        adapter = null;
                        adapter = new PhotoGraphAdapter(listData, mActivity);
                        photograph_list.setAdapter(adapter);
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 直接完成点击方法*
     */
    public void setFinish(View view) {
        if (CheckClickTime.back(this)) {
            if (!MyApp.ReadOnly) {
                if (MyApp.BackActivity == 0) {
                    IntentToActivity.intent(MyApp.activity, ReconnaissanceActivity.class);
                } else if (MyApp.BackActivity == 1) {
                    IntentToActivity.intent(MyApp.activity, ProjectMapActivity.class);
                } else if (MyApp.BackActivity == 2) {
                    IntentToActivity.intent(MyApp.activity, ProjectMapSecondActivity.class);
                }
                MyApp.BackActivity = 0;
                this.finish();
            }
        }
    }

    /**
     * 继续设计点击方法*
     */
    public void setContinue(View view) {
        if (CheckClickTime.back(this)) {
            ListenerSet.getDesignClickListener(this);
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.TypePosition:
                    hideWaitIngDialog();
                    startEditImageActivity(String.valueOf(msg.obj), Constant.TypePosition);
                    break;
                case Constant.TypePassageway:
                    String p = msg.getData().getString("1");
                    long time = msg.getData().getLong("2");
                    if (type.size() > 0) {
                        setAdd(type.get(0), p, p, MString.getMyUUID(), time);
                        type.remove(0);
                    }
                    hideWaitIngDialog();
                    break;
                case Constant.TypeEnvironmental:
                    hideWaitIngDialog();
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            showWaitDialog(-1, "处理中");
            final String path = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
            switch (requestCode) {
                case Constant.TypePosition:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            long time1 = System.currentTimeMillis();
//                            String path0 = ClipPathUtil.getPathForImage("Position");
                            String path0 = ClipPathUtil.getInstance().getImagePath() + "/" + MyApp.AppName + time1 + ".jpg";
                            CameraUtil.saveToString2(setWaterMarkWithPath(path, time1), path0);
//                            CameraUtil.saveToString(path, path0);

                            Message msg = handler.obtainMessage();
                            msg.what = Constant.TypePosition;
                            msg.obj = path0;
                            handler.sendMessage(msg);
                        }
                    }).start();

                    break;
                case Constant.TypePassageway: {//照片命名：上联杆号+“-”+当前杆号
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            type.add(Constant.TypePassageway);
                            long time = System.currentTimeMillis();
                            String type2Name = getType2Name() + time + ".jpg";
                            String p = MyApp.File.getCachaPhotoPath() + "2/" + type2Name;
                            String p2 = MyApp.File.getCachaPhotoRequestPath() + "2/" + type2Name;
//                    CameraUtil.saveToString(path, p);
//                    CameraUtil.saveToString(path, p2);
                            Bitmap bitmap = setWaterMarkWithPath(path, time);
                            CameraUtil.saveToString2(bitmap, p);
                            CameraUtil.saveToString2(bitmap, p2);

                            Bundle bundle = new Bundle();
                            bundle.putString("1", p);
                            bundle.putLong("2", time);
                            Message msg = handler.obtainMessage();
                            msg.what = Constant.TypePassageway;
                            msg.setData(bundle);
                            handler.sendMessage(msg);
                        }
                    }).start();
                }
                break;
                case Constant.TypeEnvironmental: {
                    type.add(Constant.TypeEnvironmental);
                    long time = System.currentTimeMillis();
                    String p = MyApp.File.getCachaPhotoPath() + "3/" + time + ".jpg";
                    String p2 = MyApp.File.getCachaPhotoRequestPath() + "3/" + time + ".jpg";
                    CameraUtil.saveToString(path, p);
                    CameraUtil.saveToString(path, p2);
                    if (type.size() > 0) {
                        setAdd(type.get(0), p, p, MString.getMyUUID(), time);
                        type.remove(0);
                    }

                    Message msg = handler.obtainMessage();
                    msg.what = Constant.TypeEnvironmental;
                    handler.sendMessage(msg);
                }
                break;
            }
        }
    }

    private String getType2Name() {
        String name = "";
        String beforenumber = "";
        String currnumber = "";
        if (PostParams.map != null) {
            try {
                beforenumber = PostParams.map.get(MString.before_number) + "";
                if (beforenumber.trim().contains("null") || beforenumber.trim().length() == 0) {
                    beforenumber = "";
                } else {
                    beforenumber = beforenumber + "_";
                }
                currnumber = PostParams.map.get(MString.number) + "_";
            } catch (Exception e) {
                beforenumber = "";
                currnumber = "";
            } finally {
                name = beforenumber + currnumber;
            }
        }
        return name.trim();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("userInfo", JSON.toJSONString(MyApp.userInfo));
        outState.putString("exploration_id", JSON.toJSONString(MyApp.currExploration));

    }

    private void addsavePhotosHandler() {
        savePhotoHandler = new Handler() {
            BackPhotosBean bean;
            String path_thumb, path_url;
            String photo_id;

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            JPathBean pathBean = FastJsonUtil.JsonToPathData((String) msg.obj);
                            path_thumb = pathBean.photo_thumb;
                            path_url = pathBean.photo_url;
                            photo_id = pathBean.photo_id;
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(pathBean));
                            savePhotoHandler.sendEmptyMessage(1);
                        } else {
                            MyDialog.Close();
                            ToastShow.showShort(MyApp.activity, s);
                        }
                        break;
                    case 1:
                        MyLog.L(MString.SUCCESSED + "path=" + path_thumb);
                        MyDialog.Close();
                        if (path_thumb == null || path_url == null || photo_id == null) return;
                        MyLog.L(MString.SUCCESSED + "path=更新");
                        if (type.size() > 0) {
                            setAdd(type.get(0), path_thumb, path_url, photo_id, 0);
                            type.remove(0);
                        }
                        break;
                    case 2://竣工照片：保存照片
                        MyLog.L(MString.SUCCESSED + "保存开始");
                        setAdd(Constant.TypePosition, (String) msg.obj);//保存
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(MyApp.activity, (String) msg.obj);
                        savePhotoHandler.sendEmptyMessage(1);
                        break;
                }
            }
        };
    }

    private void startEditImageActivity(String PATH, int CODE) {
        PhotosActivityUtil.IntentToEditImageActivity(this, PATH, CODE, Constant.CREATE);
    }

    public static void setUpdate(int CODE, String path) {
//        if (!MyApp.isOnLine) {
        List<BackPhoto_Bean> list = null;
        BackPhotoBean beanPhoto = null;
        switch (CODE) {
            case Constant.TypePosition:
                beanPhoto = bean.getOnePhoto();
                list = beanPhoto.getPhotoList();
                break;
            case Constant.TypePassageway:
                beanPhoto = bean.getTwoPhoto();
                list = beanPhoto.getPhotoList();
                break;
            case Constant.TypeEnvironmental:
                beanPhoto = bean.getThreePhoto();
                list = beanPhoto.getPhotoList();
                break;
        }
        if (list != null) {
            for (BackPhoto_Bean b : list) {
                if (path.contains("upload")) break;//已同步照片不操作其本地数据
                if (path.contains(b.getPhoto_url()) || path.equals(b.getPhoto_thumb())) {
                    if (b.getPhoto_id().equals(MString.code_zero)) {
                        list.remove(b);
                    } else if (TextUtils.isEmpty(b.getPhoto_id())) {//新增照片的时候photoid="";
                        list.remove(b);
                    } else {
                        b.setFlag(MString.del);
                    }
                    beanPhoto.setPhotoNum(beanPhoto.getPhotoNum() - 1);
                    break;
                }
            }
            switch (CODE) {
                case Constant.TypePosition:
                    bean.getOnePhoto().setPhotoList(list);
                    break;
                case Constant.TypePassageway:
                    bean.getTwoPhoto().setPhotoList(list);
                    break;
                case Constant.TypeEnvironmental:
                    bean.getThreePhoto().setPhotoList(list);
                    break;
            }
            SetFileUtil.setExplorationPhoto(bean);
        }
//        }
        adapter.Delect(CODE, path);
    }

    private void setAdd(int CODE, String path_thumb, String path_url, String photo_id, long time) {
        String uuid = "";
        String Create_time = time + "";
        Create_time = "";
        if (time != 0) {
            BackPhoto_Bean b = new BackPhoto_Bean();
            b.setPhoto_url(time + ".jpg");
            b.setPhoto_thumb(path_thumb);
            b.setPhoto_id("");
            b.setExploration_id(MString.getValueId(MyApp.currExploration.getExploration_id(),
                    MyApp.currExploration.getUuid()));
            uuid = MString.getMyUUID();
            b.setUuid(uuid);
            b.setCreate_time(Create_time);
            b.setFlag(MString.add);
            BackPhotoBean beanPhoto = null;
            switch (CODE) {
                case Constant.TypePosition:
                    b.setPhoto_type("1");
                    String pointNumber = PostParams.map.get(MString.number) + "_";
                    b.setPhoto_url(pointNumber + time + ".jpg");
                    beanPhoto = bean.getOnePhoto();
                    break;
                case Constant.TypePassageway:
                    b.setPhoto_type("2");
                    b.setPhoto_url(getType2Name() + time + ".jpg");
                    beanPhoto = bean.getTwoPhoto();
                    break;
                case Constant.TypeEnvironmental:
                    b.setPhoto_type("3");
                    beanPhoto = bean.getThreePhoto();
                    break;
            }
            if (beanPhoto == null) return;
            beanPhoto.setPhotoNum(bean.getOnePhoto().getPhotoNum() + 1);
            beanPhoto.getPhotoList().add(b);
            SetFileUtil.setExplorationPhoto(bean);
        }
        adapter.Refresh(CODE, path_thumb, path_url, photo_id, uuid,
                "add", MString.getValueId(MyApp.currExploration.getExploration_id(),
                        MyApp.currExploration.getUuid()), Create_time);
    }

    /**
     * 1类照片保存按钮调用方法
     * 这个照片已被设置了拖动图标
     */
    private void setAdd(int CODE, String path) {
        type.add(CODE);
        String pointNumber = PostParams.map.get(MString.number) + "_";
        long time = System.currentTimeMillis();
        String p = MyApp.File.getCachaPhotoPath() + "1/" + pointNumber + time + ".jpg";
        String p2 = MyApp.File.getCachaPhotoRequestPath() + "1/" + pointNumber + time + ".jpg";
        //保存到新路径
//        Bitmap bitmap = setWaterMarkWithPath(path, time);
//        CameraUtil.saveToString2(bitmap, p);
//        CameraUtil.saveToString2(bitmap, p2);

        CameraUtil.saveToString(path, p);
        CameraUtil.saveToString(path, p2);
        if (type.size() > 0) {
            setAdd(type.get(0), p, p, MString.getMyUUID(), time);
            type.remove(0);
        }
    }

    //生成水印照片并显示
    private Bitmap setWaterMarkWithPath(String path, long fundtime) {
        String lng = MyApp.currExploration.getLng();
        String lat = MyApp.currExploration.getLat();
//        String str1 = MyApp.currProject.getProject_name() + "：" + MyApp.currExploration.getNumber();
        String str1 = MyApp.currProject.getProject_name();
        String str2 = TimeUtil.timeSFM(new Date(fundtime));
        String str3 = lng + "," + lat;
//        Bitmap photo = BitmapFactory.decodeFile(path);//oom
        Bitmap smallBitmap = CameraUtil.getSmallBitmap(path);
        Bitmap photo = CameraUtil.compressImage(smallBitmap);

//        int width = photo.getWidth(), hight = photo.getHeight();
        int width = 480, hight = 800;
        Bitmap bitmap1 = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_8888); //建立一个空的BItMap
        Canvas canvas = new Canvas(bitmap1);//初始化画布绘制的图像到icon上

        Paint photoPaint = new Paint(); //建立画笔
        photoPaint.setDither(true); //获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);//过滤一些

        Rect src = new Rect(0, 0, width, hight);//代表要绘制的bitmap 区域
        Rect dst = new Rect(0, 0, width, hight);//代表的是要将bitmap 绘制在屏幕的什么地方
        canvas.drawBitmap(photo, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
        textPaint.setTextSize(18.0f);//字体大小
        textPaint.setTypeface(Typeface.DEFAULT);//采用默认的宽度
        textPaint.setColor(Color.YELLOW);//采用的颜色
        float y1 = hight - 80, y2 = hight - 60, y3 = hight - 40;
        float x1 = 10;
        canvas.drawText(str1, x1, y1, textPaint);//绘制上去字，开始未知x/y,采用那只笔绘制
        canvas.drawText(str2, x1, y2, textPaint);//绘制上去字，开始未知x/y,采用那只笔绘制
        canvas.drawText(str3, x1, y3, textPaint);//绘制上去字，开始未知x/y,采用那只笔绘制
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bitmap1;
    }
}
